/**
 * 权限相关
 */
export const usePermission = () => {
	
	/**
	 * 判断是否有权限
	 */
	const hasPermission = (permission, openSetting = false, confirmContent) => {
		return new Promise((resolve, reject) => {
			uni.getSetting({
				async success(res) {
					console.log('用户权限', res.authSetting, openSetting, res.authSetting[permission])
					if (Object.keys(res.authSetting).length > 0) {
						if (res.authSetting[permission] === undefined) {
							// 未请求授权
							if (openSetting) {
								uni.authorize({
									scope: permission,
									success() {
										console.log('授权成功')
										resolve(true)
									},
									fail() {
										console.log('授权失败')
										reject(false)
									}
								})
							} else {
								reject(false)
							}
						} else if (!res.authSetting[permission]) {
							// 已请求过授权，但被拒绝过
							if (openSetting) {
								uni.showModal({
									title: '授权设置',
									content: confirmContent,
									success(result) {
										if (result.confirm) {
											uni.openSetting({
												success(res) {
													console.log('设置权限', res.authSetting, res.authSetting[permission])
													resolve(res.authSetting[permission])
												}
											})
										} else {
											reject(false)
										}
									},
									fail() {
										reject(false)
									}
								})
							} else {
								reject(false)
							}
						} else {
							resolve(true)
						}
					} else {
						reject(false)
					}
				},
				fail(err) {
					reject(err)
				}
			})
		})
	}
	
	return {
		hasPermission
	}
}